import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../model/cartInfo.dart';

class CartProvide with ChangeNotifier {
  String cardString = "[]";
  List<CardInfoModel> cardList = new List();
  double allPrice = 0; //总价格
  int allGoodCount = 0;//总数量
  bool isAllCheck = true;//是否全选
  //存储购物车
  save(String goodsId,String goodsName,int count,double price,String images) async {
    SharedPreferences prefs = await SharedPreferences.getInstance(); //初始化
    cardString = prefs.getString('curtInfo');//获取数据库中的值
    var temp = cardString==null?[]:json.decode(cardString.toString());
    //把获得值转变成List
    List<Map> templist = (temp as List).cast();
    bool isHave = false; //是否已添加过
    int ival = 0;
    allGoodCount = 0;
    allGoodCount = 0;
    //是否已保存过()
    templist.forEach((item){
      if(item['goodsId'] == goodsId){
        templist[ival]['count']= item['count'] +1;
        cardList[ival].count ++;
        isHave = true;
      }
      //改变购物车数量 和总结
      if(item['isCheck']){
        allPrice += (cardList[ival].price * cardList[ival].count);
        allGoodCount +=cardList[ival].count;
      }
      ival ++ ;
    });
    if(!isHave){
      Map<String,dynamic> newGoods = {
        'goodsId':goodsId,
        'goodsName':goodsName,
        'count':count,
        'price':price,
        'images':images,
        'isCheck':true
      };
      templist.add(newGoods);
      cardList.add(CardInfoModel.fromJson(newGoods));

      allPrice += (price * count);
      allGoodCount += count;
    }

    cardString = json.encode(templist).toString();//解析成json字符串
    print('购物车中的保存的字符串数据>>>>>>>>$cardString');
    print('购物车中的当前的数据模型>>>>>>>>$cardList');
    prefs.setString('curtInfo', cardString); //保存
    notifyListeners();
  }

  //清空购物车
  remove() async {
    SharedPreferences prefs = await SharedPreferences.getInstance(); //初始化
    prefs.remove('curtInfo');
    cardList.clear();
    print('清空完成...');
    notifyListeners();
  }

  //获取购物车数据
  getCardInfo()async{
    SharedPreferences prefs = await SharedPreferences.getInstance(); //初始化
    cardString = prefs.getString('curtInfo'); //字符串的购物车数据
    cardList.clear();
    if(cardString==null){
      cardList.clear();
    }else{
      print('------------------------------------------获取数据');
      List<Map> cardStringtoList = (json.decode(cardString.toString()) as List ).cast();
      allPrice = 0;
      allGoodCount = 0;
      isAllCheck = true;
      cardStringtoList.forEach((item){
        if(item['isCheck']){
          allPrice = allPrice + item['price'] * item['count'] ;
          allGoodCount = allGoodCount + item['count'];
        }else{
          isAllCheck = false ; //没有全部选中
        }
        cardList.add(CardInfoModel.fromJson(item));
      });
    }
    print(cardList);
    notifyListeners();
  }

  //删去购物车某一项
  deletOneGoods(String goodsId) async{
    SharedPreferences prefs = await SharedPreferences.getInstance(); //初始化
    cardString = prefs.getString('curtInfo'); //字符串的购物车数据
    List<Map> cardStringtoList = (json.decode(cardString.toString()) as List ).cast();

    int fochIndex = 0;
    int cardIndex = -1;
    cardStringtoList.forEach((item){
      if(item['goodsId']==goodsId){
        cardIndex = fochIndex;
      }
      fochIndex++;
    });
    //删去
    if(cardIndex != -1){
      cardStringtoList.removeAt(cardIndex);
    }
    //删去后的cardString 字符串
    cardString= json.encode(cardStringtoList).toString();
    prefs.setString('curtInfo', cardString);

    await getCardInfo(); //重新获取数据

  }

  //改变某一项的数据 （状态 或 数量）
  changeCheckStateorCount(CardInfoModel cardItm) async{
    SharedPreferences prefs = await SharedPreferences.getInstance(); //初始化
    cardString = prefs.getString('curtInfo'); //字符串的购物车数据
    List<Map> cardStringtoList = (json.decode(cardString.toString()) as List ).cast();

    int fochIndex = 0;
    int cardIndex = -1;
    cardStringtoList.forEach((item){
      if(item['goodsId']==cardItm.goodsId){
        cardIndex = fochIndex;
      }
      fochIndex++;
    });
    //cardStringtoList为 map类   cardItm为CardInfoModel类  需转换进行赋值
    cardStringtoList[cardIndex]= cardItm.toJson();
    //将改变后的cardStringtoList转成字符串 ---》存储
    cardString = json.encode(cardStringtoList).toString();
    prefs.setString('curtInfo', cardString);

    await getCardInfo(); //重新获取数据

  }

  //设置全选
  changeAllCheckBtnState (bool isallchek) async{
     SharedPreferences prefs = await SharedPreferences.getInstance(); //初始化
     cardString = prefs.getString('curtInfo'); //字符串的购物车数据
     List<Map> cardStringtoList = (json.decode(cardString.toString()) as List ).cast();
     List<Map> newList=new List();
     cardStringtoList.forEach((item){
        var newItem = item;
        newItem['isCheck'] = isallchek;
        newList.add(newItem);
     });

     cardString = json.encode(newList).toString();
     prefs.setString('curtInfo', cardString);

     await getCardInfo(); //重新获取数据
  }

}
